/**
 * @description 微博 service
 * @author 刘煎蛋
 */

const { Blog, User, UserRelation } = require("../db/model");
const { formatUser } = require("./_format");

/**
 * 
 * @param {*} userId 用户id
 * @param {*} content 内容
 * @param {*} image 图片
 */
async function createBlog({ userId, content, image }) {
    const result = await Blog.create({
        userId,
        content,
        image
    })
    return result.dataValues;
}

/**
 * 
 * @param {*} userId 用户id
 * @param {*} pageIndex 页数
 * @param {*} pageSize 条数
 */
async function getFollowersBlogList({ userId, pageIndex = 0, pageSize = 10 }) {
    const result = await Blog.findAndCountAll({
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: [
            ['id','desc']
        ],
        include: [
            {
                model: User,
                attributes: ['userName','nickName','picture']
            }
            // {
            //     model: UserRelation,
            //     attributes: ['userId', 'followerId'],
            //     where: { userId }
            // }
        ]
    })
    let blogList = result.rows.map( row => row.dataValues );
    
    blogList = blogList.map( item => {
        const user = item.user.dataValues;
        item.user = formatUser(user);
        return item;
    })
    
    return {
        count: result.count,
        blogList
    }
}

module.exports = {
    createBlog,
    getFollowersBlogList
}